import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {MaintenanceService} from '../../maintenance.service';
import {ActivatedRoute, Router} from '@angular/router';
import {StorageService} from '../../../services/storage.service';
import {PublicService} from '../../../services/public.service';
import {EventBusService} from '../../../services/event-bus.service';
import {MatenanceObjModel} from '../../matenanceObj.model';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PUblicMethod} from '../../../services/PUblicMethod';


@Component({
  selector: 'app-malfunction-change',
  templateUrl: './malfunction-change.component.html',
  styleUrls: ['./malfunction-change.component.scss']
})
export class MalfunctionChangeComponent implements OnInit {

    formObj: MatenanceObjModel;
    options: Object = {
        '来源': [],
        '影响度': [],
        '紧急度': [],
        '故障级别': [],
        '所属系统': [],
        'departments': [],
    };
    defaultOption: Object = {
        'acceptor': null,
        'fromx': null,
        'influence': null,
        'urgency': null,
        'level': null,
        'bt_system': null,
    };
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    message: Message[] = [];               // 交互提示弹出框
    myForm: FormGroup;


    constructor(private maintenanceService: MaintenanceService,
                private router: Router,
                private fb: FormBuilder,
                private publicService: PublicService,
                private activatedRouter: ActivatedRoute,
                private eventBusService: EventBusService) { }

    ngOnInit() {
        this.formObj = new MatenanceObjModel();
        this.getDepPerson();
        this.initForm();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        (this.formObj.sid) && (this.getTrickMessage(this.formObj.sid));
        // this.maintenanceService.getFlowChart( this.initStatus).subscribe(res => {
        //     this.eventBusService.maintenance.next(res);
        // });
    }
    getTrickMessage(sid: string): void {
        this.maintenanceService.getTrick(sid).subscribe(res => {
           this.formObj.acceptor = res['acceptor'];
           this.formObj.acceptor_pid = res['acceptor_pid'];
           this.formObj.acceptor_org = res['acceptor_org'];
           this.formObj.acceptor_org_oid = res['acceptor_org_oid'];
           (this.formObj.acceptor_org_oid) && (this.getDepPerson(this.formObj.acceptor_org_oid));
        });
    }
    goBack() {
        this.router.navigate(['../malfunctionOverview'], {relativeTo: this.activatedRouter});
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.options['departments'] = newArray;
                this.formObj.acceptor_pid = newArray[0]['value']['pid'];
                this.formObj.acceptor = newArray[0]['value']['name'];
            }
        });
    }
    showTreeDialog( opType ) {
        switch (opType) {
            case 'department':
                this.display = true;
                this.publicService.getDepartmentDatas().subscribe(res => {
                    this.filesTree4 = res;
                });
        }

    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    clearTreeDialog(opType) {
        switch (opType) {
            case 'submitter':
                this.formObj.submitter = '';
                this.formObj.submitter_pid = '';
                this.formObj.submitter_org_oid = '';
                this.formObj.submitter_org = '';
                this.formObj.submitter_phone = '';
                break;
            case 'department':
                this.formObj.acceptor = '';
                this.formObj.acceptor_org = '';
                this.formObj.acceptor_org_oid = '';
                this.formObj.acceptor_pid = '';
                break;
        }

    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.acceptor_org = this.selected['label'];
        this.formObj.acceptor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    initForm() {
        this.myForm = this.fb.group({
            'acceptor': ''
        });
    }
    get acceptor() {
        // console.log('untouched', this.myForm.controls['content'].untouched);
        // console.log('required', this.myForm.controls['content'].hasError('required'));
        return this.myForm.controls['acceptor'].untouched && this.myForm.controls['acceptor'].hasError('required');
    }
    // addSelectedName() {
    //     (!this.formObj.acceptor) && (this.formObj.acceptor = this.defaultOption['acceptor']);
    // }
    // filterOptionName() {
    //     if (this.formObj.acceptor['name']) {
    //         this.formObj.acceptor = this.formObj.acceptor['name'];
    //     }
    // }
    // onSelectedDepartment(event) {
    //     let msg = this.formObj.acceptor;
    //     this.formObj.acceptor = msg['name'];
    //     this.formObj.acceptor_pid = msg['pid'];
    // }
    onChange(event) {
        this.formObj.acceptor = event['value']['name'];
        this.formObj.acceptor_pid = event['value']['pid'];
    }
    submitTrick() {
        // this.addSelectedName();
        // this.filterOptionName();
        if (!this.formObj.acceptor_org) {
            this.showError();
            this.myForm.controls['acceptor'].setValidators([Validators.required]);
            this.myForm.controls['acceptor'].updateValueAndValidity();
        }else {
            // console.log(this.formObj);
            this.formObj.status = '待接受';
            this.submitPost(this.formObj);
        }
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    submitPost(paper) {
        this.maintenanceService.changeTrick( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                  this.goBack();
                }, 1100);

            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }

}
